package com.example.searchcenter.center;

import java.util.ArrayList;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.searchcenter.R;
import com.example.searchcenter.helper.AlertDialogManager;
import com.example.searchcenter.helper.ConnectionDetector;
import com.example.searchcenter.helper.JSONParser;
import com.example.searchcenter.model.CenterItemModel;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

/***
 * 
 * @author NguyenTrung
 *
 */
@SuppressLint({ "NewApi", "ShowToast" })
public class HomeFragment extends Fragment {

	ListView list;
	TextView ver;
	TextView name;
	TextView thumbnail;
	View rootView;
	// String counter center for navDrawer
	public static final String COUNTER_CENTER = "COUNTER_CENTER";
	//public static String counter;
	EditText inputSearch;
	// Connection detector
	ConnectionDetector cd;
	// Alert dialog manager
	AlertDialogManager alert = new AlertDialogManager();

	// array hashmap
//	/ArrayList<HashMap<String, String>> centerslist = new ArrayList<HashMap<String, String>>();
	// array list centermodel
	ArrayList<CenterItemModel> centerslist = new ArrayList<CenterItemModel>();
	// URL to get JSON Array
	private static String url = "http://tinhnguyen.edu.vn/apis/getAllPlaces";
	// JSON Node Names
	public static final String TAG_CENTERS = "centers";
	public static final String TAG_ID_CENTER = "cid";
	public static final String TAG_NAME = "name";
	public static final String TAG_THUMBNAIL = "thumbnailImageUrl";
	public static final String TAG_NO = "no";
	public static final String TAG_STREET = "street";
	public static final String TAG_WARD = "ward";
	public static final String TAG_DISTRICT = "district";
	public static final String TAG_CITY = "city";
	public static final String TAG_CREATEDATE = "createDate";
	public static final String TAG_SUM = "sumPlaces";
	

	JSONArray arrayJsonCenter = null;
	CenterAdapter adapter;
	JSONObject jsonobject;
	JSONArray jsonarray;

	public HomeFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		rootView = inflater.inflate(R.layout.fragment_home, container, false);

		// Locate the EditText in listview_main.xml
		inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
		
		new ListCenters().execute();
		/**
		 * clear text in search box
		 */
		Button clearText = (Button) rootView.findViewById(R.id.clear_text);
		clearText.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				inputSearch.setText("");
			}
		});
		

		/**
		 * on action search in keyboard
		 */
		inputSearch.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				boolean handled = false;
		        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
		        	// Starting new intent
		        	Intent in = new Intent(getActivity(), ResultSearchCenters.class);
		        	// Sending inputSearcj to next activity 
		        	in.putExtra("inputSearch", inputSearch.getText().toString());
		        	startActivity(in);
		            handled = true;
		        }
		        return handled;
		    }
		});
		return rootView;
	}
	
	public static String getcounter(){
		JSONParser jParser = new JSONParser();
		// Getting JSON from URL
		JSONObject json = jParser.getJSONFromUrl(url);
		String counter = null;
		try {
			counter = json.getString(TAG_SUM);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return counter;
	}

	private class ListCenters extends AsyncTask<String, String, JSONObject> {
		private ProgressDialog pDialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Đang lấy dữ liệu, vui lòng chờ");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		@Override
		protected JSONObject doInBackground(String... args) {
			JSONParser jParser = new JSONParser();
			// Getting JSON from URL
			jsonobject = jParser.getJSONFromUrl(url);
			Log.w("JSON" , jsonobject.toString());
			return jsonobject;
		}

		@Override
		protected void onPostExecute(JSONObject json) {
			pDialog.dismiss();
			try {
				// Getting JSON Array from URL
				//centerslist = new ArrayList<HashMap<String, String>>();
				Log.w("JSON" , json.toString());
				arrayJsonCenter = json.getJSONArray(TAG_CENTERS);
				for (int i = 0; i < arrayJsonCenter.length(); i++) {

					JSONObject c = arrayJsonCenter.getJSONObject(i);
					// Storing JSON item in a Variable
					String cid = c.getString(TAG_ID_CENTER);
					String name = c.getString(TAG_NAME);
					String thumbnail = c.getString(TAG_THUMBNAIL);
					String no = c.getString(TAG_NO);
					String street = c.getString(TAG_STREET);
					String ward = c.getString(TAG_WARD);
					String district = c.getString(TAG_DISTRICT);
					String city = c.getString(TAG_CITY);
					String createDate = c.getString(TAG_CREATEDATE);
					
					// String address
					String addr = "Số "+ no + " ,Đường "+street +" ,Phường/xã "+ward
							+" ,Quận/huyện "+district +" ,thành phố "+ city;
					
					
					CenterItemModel centerItem = new CenterItemModel(cid, name, addr, createDate, thumbnail);
					centerslist.add(centerItem);
					
				}
				
				list = (ListView) rootView.findViewById(R.id.list);

				adapter = new CenterAdapter(getActivity(), centerslist);

				list.setAdapter(adapter);
				
				
				
				// Capture Text in EditText
				inputSearch.addTextChangedListener(new TextWatcher() {

					@Override
					public void afterTextChanged(Editable arg0) {
						// TODO Auto-generated method stub
						String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
						adapter.filter(text);
					}

					@Override
					public void beforeTextChanged(CharSequence arg0, int arg1,
							int arg2, int arg3) {
						// TODO Auto-generated method stub
					}

					@Override
					public void onTextChanged(CharSequence arg0, int arg1, int arg2,
							int arg3) {
						// TODO Auto-generated method stub
					}
				});
				
				
				list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {

						
						// Starting new intent
						Intent in = new Intent(getActivity(),
								DetailsCenter.class);
						// sending pid to next activity
						in.putExtra(TAG_ID_CENTER, centerslist.get(position).getCenterId());

						// starting new activity and expecting some response
						// back
						getActivity().startActivity(in);

						Toast.makeText(
								getActivity(),
								"Bạn đã chọn  "
										+ centerslist.get(+position)
												.getCenterName(),
								Toast.LENGTH_SHORT).show();
					}
				});

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}	
}